package com.translate.web.service.impl;

import com.translate.web.constant.RedisConstant;
import com.translate.web.dao.MenuMapper;
import com.translate.entity.Menu;
import com.translate.web.service.IMenuService;
import com.basic.service.impl.BaseServiceImpl;
import com.translate.vo.contract.IMenuVO;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

/**
 * 权限菜单
 * 
 * @author 111
 *
 */
@Service
public class MenuServiceImpl extends BaseServiceImpl<Menu> implements IMenuService {

	private RedisTemplate<String, List<Menu>> redisTemplate;

	public MenuServiceImpl(MenuMapper mapper) {
		super(mapper);
	}

	protected Class<Menu> getEntityClass() {
		return Menu.class;
	}

	@Override
	public <VO extends IMenuVO> List<VO> getMenus(Long[] ids, Class<VO> target, int userId) {

		List<Menu> menus = this.roleMenuRelationToCache(ids, userId);

		List<VO> vos = new ArrayList<>();

		VO vo;

		try {

			for (Menu menu : menus) {

				vo = target.newInstance();

				vo.setHidden(menu.getHidden());

				vo.setIcon(menu.getIcon());

				vo.setId(menu.getId());

				vo.setLevel(menu.getLevel());

				vo.setParentId(menu.getParentId());

				vo.setName(menu.getName());

				vo.setSort(menu.getSort());

				vo.setTitle(menu.getTitle());

				vo.setType(menu.getType());
				
				vos.add(vo);
			}
			
			return vos;

		} catch (Exception e) {

			e.printStackTrace();
		}

		return vos;

	}

	/**
	 * 角色菜单缓存
	 * 
	 * @param id
	 * @return
	 */
	public List<Menu> roleMenuRelationToCache(Long[] ids, int userId) {

		String key = RedisConstant.getMenusKey(userId);

		ValueOperations<String, List<Menu>> valueOperations = this.redisTemplate.opsForValue();

		List<Menu> order = valueOperations.get(key);

		if (null != order) {
			return order;
		}

		order = this.getDataByIds(ids);

		if (null == order) {
			order = new ArrayList<Menu>(0);

			valueOperations.set(key, order, 3, TimeUnit.SECONDS);

			return order;
		}

		valueOperations.set(key, order, 12, TimeUnit.SECONDS);

		return order;

	}

	@Autowired
	public void setRedisTemplate(RedisTemplate<String, List<Menu>> redisTemplate) {
		this.redisTemplate = redisTemplate;
	}
}